/**
 * Created by fly on 2017/1/16.
 */

$(function () {
    var parentPageId = getQueryString('parentPageId');
    var tableData = [];
    getParamsByparamTypeValue('paymentType', "#paymentType");
    getParamsByparamTypeValue('overheadType', "#allocationType");
    $('#title').html(getQueryString('projectName'));
    $('#billingDate').datepicker({
        language: 'zh-CN',
        format: 'yyyy-mm-dd',
        autoclose:true
    });

    $('#planPaymentDate').datepicker({
        language: 'zh-CN',
        format: 'yyyy-mm-dd',
        autoclose:true
    });

    $('#paymentType').on('change',function () {
        var text = $('#paymentType option:selected').text();
        if(text=='产品收入'){
            $("#taxRate").val(17);
        }else if(text=='服务收入'){
            $("#taxRate").val(6);
        }
        $("#noTaxPayment").val(formatMoney($('#billingAmount').val()/($('#taxRate').val()/100+1)));
    });

    $('#billingAmount').keyup(function(){
        $("#noTaxPayment").val(formatMoney($('#billingAmount').val()/($('#taxRate').val()/100+1)));
        $("#allocationAmount").val(formatMoney($('#billingAmount').val()*($('#allocationRatio').val()/100)));
    });

    $('#allocationRatio').keyup(function () {
        $("#allocationAmount").val(formatMoney($('#billingAmount').val()*($('#allocationRatio').val()/100)));
    })

    $("#backbtn").click(function () {
        top.topManager.openPage({
            id : getQueryString('parentPageId'),
            isClose : true
        });
    });

    $('#add').click(function () {
        if($("#costEstimateForm").valid()) {
            $.ajax({
                type: "POST",
                contentType: "application/json",
                url: ctx + "/paymentPlan/add",
                data: JSON.stringify({
                    projectId: getQueryString('id'),
                    paymentType: $("#paymentType").val(),
                    billingDate: $("#billingDate").val(),
                    billingAmount: $("#billingAmount").val(),
                    taxRate: $("#taxRate").val(),
                    noTaxPayment: unformatMoney($("#noTaxPayment").val()),
                    planPaymentDate: $("#planPaymentDate").val(),
                    allocationType: $("#allocationType").val(),
                    allocationRatio: $("#allocationRatio").val(),
                    allocationAmount: unformatMoney($("#allocationAmount").val().replace(/,/g, '')),
                    remark: $("#remark").val()
                }),
                success: function (data) {
                    if (data.code == 200) {
                        alert(data.data);
                    } else {
                        alert(data.msg);
                    }
                    $('#table').bootstrapTable('refresh', {url: ctx + '/paymentPlan/query'});
                }
            });
        }
    });

    initTable();

    var changeForm = $("#changeForm").validate({
        errorElement: 'span',
        errorClass: 'text-error',
        rules: {
            changeRemark: {
                required: true,
                trim: true
            }
        },
        messages: {
            changeRemark: {
                required: '备注不能为空',
                trim: '备注不能为空'
            }
        },
        errorPlacement: function (error, element) {
            error.addClass("ui red pointing label transition");
            $(element.parent()).append(error);
        },
        highlight: function (element, errorClass, validClass) {
            $(element).parents(".row").addClass(errorClass);
        },
        unhighlight: function (element, errorClass, validClass) {
            $(element).parents(".row").removeClass(errorClass);
        }
    });
    var finishForm = $("#finishForm").validate({
        errorElement: 'span',
        errorClass: 'text-error',
        rules: {
            realBillDate: {
                required: true,
                trim:true
            }
        },
        messages: {
            realBillDate: {
                required: '实际开票日期不能为空',
                trim:'实际开票日期不能为空'
            }
        },
        errorPlacement: function (error, element) {
            error.addClass("ui red pointing label transition");
            $(element.parent()).append(error);
        },
        highlight: function (element, errorClass, validClass) {
            $(element).parents(".row").addClass(errorClass);
        },
        unhighlight: function (element, errorClass, validClass) {
            $(element).parents(".row").removeClass(errorClass);
        }
    });

    $('#realBillDate').datepicker({
        language: 'zh-CN',
        format: 'yyyy-mm-dd',
        autoclose:true
    });

});

function  initTable() {
    $('#table').bootstrapTable({
        height: top.frameHeight*0.7 ,
        url: ctx + '/paymentPlan/query', //这个接口需要处理bootstrap table传递的固定参数
        method:'post',
        dataType: "json",
        cache: false,   //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        contentType:"application/x-www-form-urlencoded; charset=UTF-8",   //post请求,content type默认设置为 text/plain,在服务端直接通过 @RequestParam参数映射是获取不到的。
        striped: true,      //是否显示行间隔色
        sortable: false,      //是否启用排序
        sortOrder: "asc",     //排序方式
        queryParams : queryParams,    //前端调用服务时，会默认传递上边提到的参数，如果需要添加自定义参数，可以自定义一个函数返回请求参数
        responseHandler:function(res){
            //远程数据加载之前,处理程序响应数据格式,对象包含的参数: 我们可以对返回的数据格式进行处理
            //在ajax后我们可以在这里进行一些事件的处理
            tableData = res.data;
            return tableData;
        },
        strictSearch: true,
        clickToSelect: true,    //是否启用点击选中行
        searchOnEnterKey: true,
        showFooter: true,
        onLoadSuccess:function () {
            $('[data-toggle="tooltip"]').tooltip();
        },
        columns: [{
            title: '序号',
            align: 'center',
            width: 50,
            formatter: function (value, row, index) {
                return index+1;
            },
            footerFormatter: function (value) {
                return '合计';
            }
        },{
            field: 'id',
            visible:false
        },{
            field: 'paymentTypeName',
            align: 'center',
            width: 100,
            title: '预计收款类型'
        },{
            field: 'billingDate',
            align: 'center',
            width: 100,
            title: '预计开票日期',
            formatter: function (value, row, index) {
                return $.myTime.UnixToDate(Number(value));
            }
        },{
            field: 'billingAmount',
            align: 'right',
            width: 100,
            title: '预计开票金额',
            formatter: function (value, row, index) {
                //格式化金额
                return formatMoney(value);
            },
            footerFormatter: function (value) {
                var sum = 0;
                for(var i in value){
                    if(value[i].statusName =='作废') {
                        continue;
                    }else{
                        sum+=Number(value[i].billingAmount);
                    }
                }
                return sum<0?'<span style="color:red">' + formatMoney(sum) + '</span>':formatMoney(sum);
            }
        },{
            field: 'taxRate',
            align: 'right',
            width: 100,
            title: '税率',
            formatter: function (value, row, index) {
                return value + '%';
            }
        },{
            field: 'noTaxPayment',
            align: 'right',
            width: 100,
            title: '预计收入金额',
            formatter: function (value, row, index) {
                //格式化金额
                return formatMoney(value);
            },
            footerFormatter: function (value) {
                var sum = 0;
                for(var i in value){
                    if(value[i].statusName =='作废') {
                        continue;
                    }else{
                        sum+=Number(value[i].noTaxPayment);
                    }
                }
                return sum<0?'<span style="color:red">' + formatMoney(sum) + '</span>':formatMoney(sum);
            }
        },{
            field: 'planPaymentDate',
            align: 'center',
            width: 100,
            title: '预计收款日期',
            formatter: function (value, row, index) {
                return $.myTime.UnixToDate(Number(value));
            }
        },{
            field: 'statusName',
            align: 'center',
            width: 100,
            title: '状态'
        },{
            field: 'allocationTypeName',
            align: 'center',
            width: 100,
            title: '分摊类型'
        }, {
            field: 'allocationRatio',
            align: 'right',
            width: 100,
            title: '分摊比例',
            formatter: function (value, row, index) {
                return value + '%';
            }
        }, {
            field: 'allocationAmount',
            align: 'right',
            width: 100,
            title: '预计分摊金额',
            formatter: function (value, row, index) {
                return formatMoney(value);
            }
        },{
            field: 'operator',
            align: 'center',
            width: 100,
            title: '操作人'
        },{
            field: 'createDate',
            align: 'center',
            width: 100,
            title: '操作时间',
            formatter: function (value, row, index) {
                return $.myTime.UnixToDate(Number(value));
            }
        },{
            field: 'remark',
            align: 'left',
            title: '备注',
            formatter: function (value, row, index) {
                var html = '';
                var arr = value.split('|')
                for(var i in arr){
                    html+='<p title="'+arr[i]+'">'+arr[i]+'</p>';
                }
                return html
            }
        },{
            title: '操作',
            align: 'center',
            width: 100,
            formatter: function (value, row, index) {
                if(row.statusName == '新建') {
                    var a = '<a href="javascript:void(0);" onclick="changeModal(' + row.id + ',\''+row.remark+'\')" title="作废">作废</a>&nbsp;&nbsp;';

                    //根据角色权限判断是否要显示
                    var b = '';
                    var roleFuncCode = JSON.parse(sessionStorage.getItem("roleFuncCode"));
                    if ($.inArray("/payment/edit", roleFuncCode) >= 0) {
                        b = '<a href="javascript:void(0);" onclick="finishModal(' + index + ')" title="完成开票">完成开票</a>&nbsp;&nbsp;';
                    }

                    return a + b;
                }else{
                    return ''
                }
            }
        }]
    });

}

function queryParams(params){
    var loginCode = window.sessionStorage.getItem("managerUser");
    return {
        projectId : getQueryString('id'),
        loginCode:loginCode
    }
}

function changeModal(id,remark){
    $('#changeModal').modal('show');
    $('#saveChange').off('click');
    $('#saveChange').on('click',function () {

        if($("#changeForm").valid()) {
            $.ajax({
                type: "POST",
                contentType: "application/json",
                url: ctx + '/paymentPlan/invalid',
                data: JSON.stringify({
                    id: id,
                    remark: $('#changeRemark').val() == '' ? remark : remark+'|'+$('#changeRemark').val()
                }),
                success: function (data) {
                    $('#changeModal').modal('hide');
                    document.getElementById("changeForm").reset();
                    if(data.code==200){
                        alert(data.msg);
                        $('#table').bootstrapTable('refresh', {url: ctx + '/paymentPlan/query'});
                    }else{
                        alert(data.msg);
                    }
                }
            })
        }
    });
}

function finishModal(index){
    $('#finishModal').modal('show');
    $('#saveFinish').off('click');
    $('#saveFinish').on('click',function () {
        if($("#finishForm").valid()) {
            tableData[index].remark = tableData[index].remark+ '|'+ $('#finishRemark').val();
            tableData[index].realBillDate = $("#realBillDate").val();
            $.ajax({
                type: "POST",
                contentType: "application/json",
                url: ctx + '/paymentPlan/makeInvoice',
                data: JSON.stringify(tableData[index]),
                success: function (data) {
                    $('#finishModal').modal('hide');
                    document.getElementById("finishForm").reset();
                    if(data.code==200){
                        alert(data.msg);
                        $('#table').bootstrapTable('refresh', {url: ctx + '/paymentPlan/query'});
                    }else{
                        alert(data.msg);
                    }
                }
            })
        }
    });
}

$('#hideChange').click(function () {
    $('#changeModal').modal('hide');
});

$('#hideFinish').click(function () {
    $('#finishModal').modal('hide');
});

